var code = require('./code.js');
var io = require('./io.js');

var locationInfoReport = function(socket, head ){
	var sim = head.TerminalPhoneNum;
	var response = code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(sim),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x02,0x00],
			0x00
			)
		);
	socket.write(response,'hex');
};

var batchLocationInfoReport = function(socket, head){
	var sim = head.TerminalPhoneNum;
	var response = code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(sim),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x07,0x04],
			0x00
		)
	);
	socket.write(response,'hex');
};

var locationInfoRespond = function(socket, head, obj ){};
var textTranslate = function(key, head, obj){};

var heartbeat = function( socket, head ){
	var response = code.generalResponse(
		[0x80,0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		code.int2bytes2(head.MsgNumber),
		[0x00,0x02],
		0x00
	);
	socket.write(response,'hex');
};
var very_map = {};
var login = function( socket, head, obj ){
	io.send('login',obj);
	var sim = head.TerminalPhoneNum;
	var very = ''+ sim + '0000000';
	very_map[sim] = very;
	var response = code.makeMessage(
		[0x81,0x00],
		code.str2Bcd(sim),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			code.int2bytes2(0)[1],
			code.str2unicode(very)
		)
	);
	socket.write(response,'hex');
};

var logout = function( socket, head ){
	io.send('logout', head );
	delete very_map[head.TerminalPhoneNum];
	var response = code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x01,0x01],
			0x00
		)
	);
	socket.write(response,'hex');
};

var authentication = function( socket, head ){
	var sim = head.TerminalPhoneNum;
	io.send('auth',very_map[sim]);
	var response = code.makeMessage(
			[0x80,0x01],
			code.str2Bcd(sim),
			code.getSerialNumber(),
			[].concat(
				code.int2bytes2(head.MsgNumber),
				[0x01,0x02],
				0x00
			)
		);
	socket.write(response,'hex');
};

var response = function(res){
	io.send('response', res);
};

module.exports = {
	heartbeat : heartbeat,// 终端心跳
	login : login,// 终端注册
	logout : logout,//终端注销
	authentication : authentication,//终端鉴权
	locationInfoReport : locationInfoReport,// 位置信息汇报
	locationInfoRespond : locationInfoRespond,// 位置信息查询应答
	batchLocationInfoReport : batchLocationInfoReport,// 批量位置信息汇报
	textTranslate : textTranslate,// 终端上传文本报文解析
	response : response
};
